package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

@Slf4j
@org.springframework.stereotype.Service
public class UserUserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    private String imagePath = "C:\\Users\\高书恒\\Desktop\\a.jpg";

    /**
     * @param userName
     * @param userPwd
     * @return
     */
    @Override
    public boolean login(String userName, String userPwd) {
        Integer user = userMapper.login(userName, userPwd);
        log.info("登录: {}", user);
        if (user != null) return true;
        return false;
    }


    /**
     * @param userName
     * @param userPwd
     * @return
     */
    @Override
    public boolean register(String userName, String userPwd) throws IOException {
        User user = userMapper.getUserByName(userName);
//        log.info("注册: {}", user);
        if (user == null) {
            // 读取图片文件并进行Base64编码
            String avatar = "data:image/jpg;base64," + Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of(imagePath)));
            userMapper.register(userName, userPwd);

            userMapper.insertAvatar(userName, avatar);
            return true;
        } else return false;
    }


    /**
     * @param name
     */
    public String getAvatarByName(String name) {
        return userMapper.getAvatarByName(name);
    }


    /**
     * @param userName
     * @param userAvatar
     */
    public void updateUserAvatar(String userName, String userAvatar) {
        String avatar = userMapper.getAvatarByName(userName);
        if (avatar == null) userMapper.insertAvatar(userName, userAvatar);
        else userMapper.updateAvatar(userName, userAvatar);
    }


}
